package com.comp3111.happymeal;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.configuration.Configuration;
import com.configuration.Owner;
import com.controller.MealCommentFetch;
import com.controller.MealFetch;
import com.controller.UserFetch;
import com.object.Meal;
import com.object.MealComment;
import com.object.User;
import com.user.Helper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;

public class FollowingPageActivity extends NavigationDrawerActivity {
	
	private ListView followingListView;
    private SimpleAdapter followingAdapter;
    /*
    private ListView listView2;
    private SimpleAdapter adapter2;
    private ListView listView3;
    private SimpleAdapter adapter3;
    */
    private List<Integer> commentUserIdList;
    private List<Integer> commentIdList;
    
    Drawable mealPicture;
    Drawable userProfilePicture;
    String userProfilePictureDrawableURL;
    String mealPictureDrawableURL;
    
    //Constant for displaying listview
    final int NUM_COMMENT = 20;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_using_listview_only);
        createDrawer();
        
        followingListView = (ListView)findViewById(R.id.page_using_listview_only_listview);
        followingAdapter = new SimpleAdapter(this, getActivity(), R.layout.comment_food_listview,
				new String[]{"comment_food_user_review_pic","comment_food_brief_description","comment_food_time","comment_food_comments", "comment_food_love_pic"},
				new int[]{R.id.comment_food_user_review_pic,R.id.comment_food_brief_description, R.id.comment_food_time, R.id.comment_food_comments,R.id.comment_food_love_pic});
        followingListView.setAdapter(followingAdapter);
        followingAdapter.setViewBinder(new ViewBinder(){
        	public boolean setViewValue(View view,Object data,String textRepresentation){
				if(view instanceof ImageView && data instanceof Drawable){
					ImageView iv=(ImageView)view;
					iv.setImageDrawable((Drawable)data);
					return true;
				}
				else return false;
			}
        });
        followingListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
            	//Handle no comment
            	if(commentUserIdList.size()==0){
            		return;
            	}
            	
            	int userId = commentUserIdList.get(position);
            	//Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(FollowingPageActivity.this,UserProfileActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("USERID",Integer.toString(userId).trim());
					
				//Go to next page
				startActivity(intentPass);
				
				//return false;
            }
        }); 
        
        
        Helper.setListViewHeightBasedOnChildren(followingListView);
        
        //Release unused ram
        System.gc();
        /*
        listView2 = (ListView)findViewById(R.id.listView2);
        adapter2 = new SimpleAdapter(this, getData2(), R.layout.comment_food_listview,
				new String[]{"user_review_pic","brief_description","time", "comments", "love_pic"},
				new int[]{R.id.user_review_pic, R.id.brief_description, R.id.time, R.id.comments, R.id.love_pic});
        listView2.setAdapter(adapter2);
        
        listView3 = (ListView)findViewById(R.id.listView3);
        adapter3 = new SimpleAdapter(this, getData3(), R.layout.love_food_listview,
				new String[]{"user_review_pic","brief_description","time"},
				new int[]{R.id.user_review_pic, R.id.brief_description, R.id.time});
        listView3.setAdapter(adapter3);
        */
    }
    
    
    private List<Map<String, Object>> getActivity() {
    	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		commentUserIdList = new ArrayList<Integer>();
		commentIdList = new ArrayList<Integer>();
		
		MealCommentFetch mealCommentFetch = new MealCommentFetch();
		List<MealComment> mealCommentList = mealCommentFetch.fetchMealCommentByFollowerId(Owner.id);
		UserFetch userFetch = new UserFetch();
		MealFetch mealFetch = new MealFetch();
		
		if(mealCommentList != null){
			int counter = 0;
			for(MealComment mealComment : mealCommentList){
		    	// Display at most 5 comments
		    	if(counter > NUM_COMMENT-1){
		    		break;
		    	}else{
		    		counter++;
		    	}
							
				//drawableURL = Configuration.baseURL + restaurant.getProfilePicture();
				Map<String, Object> map = new HashMap<String, Object>();
				
				User user = userFetch.fetchUserById(mealComment.getUser());
				Meal meal = mealFetch.fetchMealById(mealComment.getMeal());
				
				if(user.getProfilePicture()!=null){
					
					userProfilePictureDrawableURL = Configuration.baseURL + user.getProfilePicture();
					
					
					//Start a new thread and use POST method to send telephone and passcode to authURL
			        //Start a new thread to attempt Login (requirement when connecting online)
					Thread attemptThread = new Thread(new Runnable(){  
						public void run(){  						
							userProfilePicture = loadImageFromURL(userProfilePictureDrawableURL);		
						}
					});  
					attemptThread.start();
					
					while(attemptThread.isAlive()){
						//Wait for server response
					}
				}
				
				/*
				 * TODO : Add one more field for displaying mealPicture
				 */
				map.put("comment_food_user_review_pic", userProfilePicture);
				map.put("comment_food_brief_description", userFetch.fetchUserNameById(mealComment.getUser()) + " commented " + meal.getName());
				map.put("comment_food_comments", mealComment.getComment());
				map.put("comment_food_time", mealComment.getCreateDate());
				
				if(mealCommentFetch.isLikedByUser(meal.getId(),user.getId())){
					map.put("comment_food_love_pic", R.drawable.love);
				}else{
					map.put("comment_food_love_pic", R.drawable.nolove);
				}
				
				list.add(map);
				
				//List containing restaurant id in order
				commentUserIdList.add(mealComment.getUser());
				commentIdList.add(mealComment.getId());
	    	}
		    
		    
	    }else{
	    	Map<String, Object> map = new HashMap<String, Object>();
	    	map.put("comments","No comments yet!");
	    	list.add(map);
	    }
		return list;
	}
    
    private Drawable loadImageFromURL(String url){
        try{
        	InputStream is = (InputStream) new URL(url).getContent();
            Bitmap tmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeStream(is),Configuration.THUMBSIZE,Configuration.THUMBSIZE);
            return new BitmapDrawable(getResources(), tmp);
            /*
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable draw = Drawable.createFromStream(is, "src");
            return draw;
            */
        }catch (Exception e) {
            //TODO handle error
            Log.i("loadingImg", e.toString());
            return null;
        }
    }
    
    /*
    private List<Map<String, Object>> getData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_review_pic", R.drawable.profile_pic_2);
		map.put("brief_description", "Kim Sung commented a restaurant");
		map.put("time", "29/3/2014 11:28PM");
		map.put("comments", "The restaurant is good. The staff are nice.");
		map.put("user_rating", "Rating: 5/5");
		list.add(map);
		
		return list;
	}
    private List<Map<String, Object>> getData2() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_review_pic", R.drawable.profile_pic_2);
		map.put("brief_description", "Kim Sung commented a food");
		map.put("time", "29/3/2014 11:28PM");
		map.put("comments", "It is fatastic, delicious, good, not bad.");
		map.put("love_pic", R.drawable.love);
		list.add(map);
		
		return list;
	}
    private List<Map<String, Object>> getData3() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_review_pic", R.drawable.profile_pic_2);
		map.put("brief_description", "Kim Sung loved Baby Mac");
		map.put("time", "29/3/2014 11:28PM");
		list.add(map);
		
		return list;
	}
	*/
}